package tt.dz.biz.dao.channel;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import tt.dz.common.DateUtil;
import tt.dz.common.LogUtil;
import tt.dz.common.PayChannelAccountCheckEnum;
import tt.dz.vo.ChannelCheckdetailVO;
import tt.dz.vo.WechatBillRecordVO;

@Repository("weChatChannelCheckDao")
public class WeChatChannelCheckDaoImp
  extends ChannelCheckDaoImp
{
  private static final String CHANNEL_NO = PayChannelAccountCheckEnum.WECHAT.channelCode();
  private static final String COMPARE_SQL = "SELECT a.channel_code,a.accounting_date as tran_accounting_date,a.trade_no,a.plat_time,a.payment_amount,  a.pay_state_code,a.pay_type_code,b.total_amount as thd_amount,b.trade_state,b.wechat_order,b.pub_account_ID    from ms_tran_info a LEFT JOIN  wechat_bill_record b on    a.order_no=b.merchant_order   where a.channel_code=:channelCode and  (a.check_account_sate is null or a.check_account_sate='00') ";
  private static final String UPDATE_WECHAT_BILL_RECORD = "update wechat_bill_record set ischeck=1 where pub_account_id=:pubAccountId and wechat_order=:wechatOrder ";
  private static final String INSERT_WECHAT_BILL_RECORD = "insert into wechat_bill_record(trade_time,pub_account_id,merchant_no,sub_merchant_no,device_id,wechat_order,merchant_order,user_identity,trade_type,trade_state,pay_bank,currency,total_amount,redpacket_amount,refund_apply_time,refund_success_time,wechat_refund_order,merchant_refund_order,refund_amount,refund_redpacket_amount,refund_type,refund_state,goods_name,merchant_datapacket,handling_charge,rate,ischeck,import_time)  values(:tradeTime,:pubAccountId,:merchantNo,:subMerchantNo,:deviceId,:wechatOrder,:merchantOrder,:userIdentity,:tradeType,:tradeState,:payBank,:currency,:totalAmount,:redpacketAmount,:refundApplyTime,:refundSuccessTime,:wechatRefundOrder,:merchantRefundOrder,:refundAmount,:refundRedpacketAmount,:refundType,:refundState,:goodsName,:merchantDatapacket,:handlingCharge,:rate,:ischeck,CURRENT_TIMESTAMP ) ";
  public static final String QUERY_WECHAT_BILL_RECORD = "select  trade_time,pub_account_id,merchant_no,sub_merchant_no,device_id,wechat_order,merchant_order,user_identity,trade_type,trade_state,pay_bank,currency,total_amount,redpacket_amount,refund_apply_time,refund_success_time,wechat_refund_order,merchant_refund_order,refund_amount,refund_redpacket_amount,refund_type,refund_state,goods_name,merchant_datapacket,handling_charge,rate,ischeck,import_time  from wechat_bill_record where 1=1 ";
  
  public List<WechatBillRecordVO> getWechatBillRecord()
  {
    MapSqlParameterSource paramMap = new MapSqlParameterSource();
    Calendar importTime = Calendar.getInstance();
    importTime.add(5, -1);
    paramMap.addValue("importTime", importTime.getTime());
    return queryForList("select  trade_time,pub_account_id,merchant_no,sub_merchant_no,device_id,wechat_order,merchant_order,user_identity,trade_type,trade_state,pay_bank,currency,total_amount,redpacket_amount,refund_apply_time,refund_success_time,wechat_refund_order,merchant_refund_order,refund_amount,refund_redpacket_amount,refund_type,refund_state,goods_name,merchant_datapacket,handling_charge,rate,ischeck,import_time  from wechat_bill_record where 1=1  and import_time>=:importTime  order by trade_time desc ", paramMap, WechatBillRecordVO.class);
  }
  
  public WechatBillRecordVO getWechatBillRecordByWechatOrder(final String pubAccountId, final String wechatOrder)
  {
    try
    {
    	  MapSqlParameterSource paramMap = new MapSqlParameterSource();
    	  paramMap.addValue("pubAccountId", pubAccountId);
    	return (WechatBillRecordVO)this.jdbcTemplate.queryForObject("select  trade_time,pub_account_id,merchant_no,sub_merchant_no,device_id,wechat_order,merchant_order,user_identity,trade_type,trade_state,pay_bank,currency,total_amount,redpacket_amount,refund_apply_time,refund_success_time,wechat_refund_order,merchant_refund_order,refund_amount,refund_redpacket_amount,refund_type,refund_state,goods_name,merchant_datapacket,handling_charge,rate,ischeck,import_time  from wechat_bill_record where 1=1  and pub_account_Id=:pubAccountId and wechat_order=:wechatOrder ", paramMap,new BeanPropertyRowMapper(WechatBillRecordVO.class));
    }
    catch (DataAccessException e)
    {
      LogUtil.debug("查询微信账户对象为空,微信公众号:" + pubAccountId + ",微信订单号:" + wechatOrder);
    }
    return null;
  }
  
  public int[] insertWechatBillRecord(List<WechatBillRecordVO> wechatBillRecordList)
    throws Exception
  {
    return batchSave("insert into wechat_bill_record(trade_time,pub_account_id,merchant_no,sub_merchant_no,device_id,wechat_order,merchant_order,user_identity,trade_type,trade_state,pay_bank,currency,total_amount,redpacket_amount,refund_apply_time,refund_success_time,wechat_refund_order,merchant_refund_order,refund_amount,refund_redpacket_amount,refund_type,refund_state,goods_name,merchant_datapacket,handling_charge,rate,ischeck,import_time)  values(:tradeTime,:pubAccountId,:merchantNo,:subMerchantNo,:deviceId,:wechatOrder,:merchantOrder,:userIdentity,:tradeType,:tradeState,:payBank,:currency,:totalAmount,:redpacketAmount,:refundApplyTime,:refundSuccessTime,:wechatRefundOrder,:merchantRefundOrder,:refundAmount,:refundRedpacketAmount,:refundType,:refundState,:goodsName,:merchantDatapacket,:handlingCharge,:rate,:ischeck,CURRENT_TIMESTAMP ) ", wechatBillRecordList);
  }
  
  protected List<ChannelCheckdetailVO> getChannelCheckDetailList()
    throws Exception
  {
    LogUtil.info("微信渠道对账，会计账务日期：" + DateUtil.getStringByYMD(this.accountingDate));
    List<ChannelCheckdetailVO> result = new ArrayList();
    MapSqlParameterSource parameters = new MapSqlParameterSource();
    parameters.addValue("channelCode", getChannelNo());
    
    List<Map<String, Object>> checkDetailList = findListBySql("SELECT a.channel_code,a.accounting_date as tran_accounting_date,a.trade_no,a.plat_time,a.payment_amount,  a.pay_state_code,a.pay_type_code,b.total_amount as thd_amount,b.trade_state,b.wechat_order,b.pub_account_ID    from ms_tran_info a LEFT JOIN  wechat_bill_record b on    a.order_no=b.merchant_order   where a.channel_code=:channelCode and  (a.check_account_sate is null or a.check_account_sate='00') ", parameters);
    ChannelCheckdetailVO channelCheckdetailVo = null;
    List<Map<String, String>> aliparamList = new ArrayList();
    List<Map<String, String>> traninfoparamList = new ArrayList();
    String channelCode = null;
    String tradeNo = null;
    Date tranAccountingDate = null;
    Date platTime = null;
    BigDecimal paymentAmount = null;
    Integer payStateCode = null;
    Integer payTypeCode = null;
    BigDecimal thdAmount = null;
    String tradeState = null;
    String wechatOrder = null;
    String pubAccountID = null;
    for (Map<String, Object> checkDetail : checkDetailList)
    {
      channelCode = (String)checkDetail.get("channelCode");
      tradeNo = (String)checkDetail.get("tradeNo");
      tranAccountingDate = (Date)checkDetail.get("accountingDate");
      platTime = (Date)checkDetail.get("platTime");
      paymentAmount = (BigDecimal)checkDetail.get("paymentAmount");
      payStateCode = (Integer)checkDetail.get("payStateCode");
      payTypeCode = (Integer)checkDetail.get("payTypeCode");
      thdAmount = (BigDecimal)checkDetail.get("thdAmount");
      tradeState = (String)checkDetail.get("tradeState");
      tradeState = tradeState != null ? tradeState : "";
      wechatOrder = (String)checkDetail.get("wechatOrder");
      pubAccountID = (String)checkDetail.get("pubAccountID");
      if (paymentAmount != null)
      {
        thdAmount = thdAmount != null ? thdAmount : BigDecimal.ZERO;
        if (paymentAmount.compareTo(thdAmount) != 0)
        {
          channelCheckdetailVo = new ChannelCheckdetailVO();
          channelCheckdetailVo.setChannelCode(channelCode);
          channelCheckdetailVo.setAccountingCode(this.accountingDate);
          channelCheckdetailVo.setTradeNo(tradeNo);
          channelCheckdetailVo.setTranDate(tranAccountingDate);
          channelCheckdetailVo.setTranAmount(paymentAmount);
          channelCheckdetailVo.setPlatPayTime(platTime);
          channelCheckdetailVo.setPlatPayState(payStateCode);
          channelCheckdetailVo.setPlatPayType(payTypeCode);
          



          channelCheckdetailVo.setCheckState(Integer.valueOf(1));
          channelCheckdetailVo.setCheckResult(Integer.valueOf(5));
          channelCheckdetailVo.setMannulFlag(Integer.valueOf(0));
          result.add(channelCheckdetailVo);
        }
      }
      if ((wechatOrder != null) && (pubAccountID != null) && (!"".equals(wechatOrder)) && (!"".equals(pubAccountID)))
      {
        Map<String, String> param = new HashMap();
        param.put("wechatOrder", wechatOrder);
        param.put("pubAccountId", pubAccountID);
        aliparamList.add(param);
      }
      Map<String, String> param = new HashMap();
      param.put("tradeNo", tradeNo);
      param.put("checkAccountSate", "02");
      traninfoparamList.add(param);
    }
    batchupdateBySql("update wechat_bill_record set ischeck=1 where pub_account_id=:pubAccountId and wechat_order=:wechatOrder ", (Map[])aliparamList.toArray(new Map[0]));
    batchupdateBySql("update ms_tran_info set check_account_sate=:checkAccountSate where trade_no=:tradeNo ", (Map[])traninfoparamList.toArray(new Map[0]));
    return result;
  }
  
  protected String getChannelNo()
  {
    return CHANNEL_NO;
  }
}
